package utils

import (
	"reflect"
	"strings"
)

//// ReflectToMap 基于反射将对象转换为MAP
//func ReflectToMap(o interface{}) map[string]interface{} {
//	objValue := reflect.ValueOf(o)
//	objType := objValue.Type()
//
//	data := make(map[string]interface{})
//
//	for i := 0; i < objValue.NumField(); i++ {
//		field := objValue.Field(i)
//		key := objType.Field(i).Name
//		value := field.Interface()
//		data[key] = value
//	}
//
//	return data
//}

// ReflectToMap 基于反射将对象转换为MAP
func ReflectToMap(o interface{}) map[string]interface{} {
	m := make(map[string]interface{})
	objValue := reflect.ValueOf(o)
	if objValue.Kind() == reflect.Ptr {
		objValue = objValue.Elem()
	}
	if objValue.Kind() != reflect.Struct {
		return m
	}

	relType := objValue.Type()
	for i := 0; i < relType.NumField(); i++ {
		name := relType.Field(i).Name
		tag := relType.Field(i).Tag.Get("json")
		if tag != "" {
			index := strings.Index(tag, ",")
			if index == -1 {
				name = tag
			} else {
				name = tag[:index]
			}
		}
		m[name] = objValue.Field(i).Interface()
	}
	return m
}
